#include "head.h"

int mkdirFunc(const int cur_dir_id,const char* dirname,const char *username,char *error_buf)
{
    //id不合法
    if(cur_dir_id<=0)
    {
        strcpy(error_buf,"id is not legal");
        return -1;
    }

    //连接mysql的服务端
    MYSQL* mysql=mysql_init(NULL);
    MYSQL* ret=mysql_real_connect(mysql,"localhost","root","123","os",0,NULL,0);
    if(ret==NULL)
    {
        sprintf(error_buf,"%s:%s","mysql_real_connect",mysql_error(mysql));
        return -1;
    }

    //1.先判断是否有相同目录
    char sql[500]={0};
    sprintf(sql,"select filename from vft where parent_id=%d;",cur_dir_id);
    int qret=mysql_query(mysql,sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }
    MYSQL_RES* rows=mysql_store_result(mysql);
    for(unsigned i=0;i<mysql_num_rows(rows);++i)
    {
        MYSQL_ROW row=mysql_fetch_row(rows);
        for(unsigned j=0;j<mysql_num_fields(rows);++j){
            //遍历同一目录下的所有文件
            if(strcmp(row[j],dirname)==0)
            {
                //说明有相同的目录
                strcpy(error_buf,"exit same dir!");
                /* printf("exit same dir!\n"); */
                return -1;
            }
        }
    }
    //判断是文件还是目录
    sprintf(sql,"select path,type from vft where id=%d;",cur_dir_id);
    qret=mysql_query(mysql,sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }

    rows=mysql_store_result(mysql);
    MYSQL_ROW  row=mysql_fetch_row(rows);
    if(mysql_num_rows(rows)==0)
    {
        strcpy(error_buf,"vft table don't exit the meeting criterial rows");
        /* printf("vft table don't exit the meeting criterial rows\n"); */
        return -1;
    }
    //判断是不是文件类型
    if(strcmp(row[1],"d"))
    {
        strcpy(error_buf,"The file corresponding to id isn't a dir!");
        /* printf("The file corresponding to id isn't a dir!\n"); */
        return -1;
    }

    //将新目录的path合起来
    char new_path[200]={0};
    strcat(new_path,row[0]);
    strcat(new_path,"/");
    strcat(new_path,dirname);

    //3.插入新的一行
    bzero(sql,sizeof(sql));
    sprintf(sql,"insert into vft (filename,user,parent_id,type,path) values('%s','%s','%d','d','%s');",dirname,username,cur_dir_id,new_path);
    printf("sql=%s\n",sql);
    qret=mysql_query(mysql,sql);
    if(qret!=0)
    {
        sprintf(error_buf,"%s:%s","mysql_query",mysql_error(mysql));
        return -1;
    }

    mysql_close(mysql);
    return 0;
}
